<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Invoice extends Model
{
    protected $table = 'invoices';

    // 不使用自增主键，使用雪花ID
    public $incrementing = false;
    protected $keyType = 'string';

    // 开票类型常量
    const BILLING_TYPE_6_REGULAR = '6_regular';           // 6%普票
    const BILLING_TYPE_6_SPECIAL = '6_special';           // 6%专票  
    const BILLING_TYPE_DIFFERENTIAL_REGULAR = 'differential_regular'; // 差额普票

    // 开票类目常量
    const BILLING_CATEGORY_IT_SERVICES = 'it_services';   // 信息技术服务

    // 开票状态常量
    const STATUS_NEW = '新建';
    const STATUS_BILLING = '开票中';
    const STATUS_BILLED = '已开票';
    const STATUS_REJECTED = '已拒绝';
    const STATUS_VOIDED = '已作废';

    protected $fillable = [
        'id',
        'invoice_number',
        'tenant_id',
        'landing_company_id',
        'invoice_amount',
        'billing_type',
        'billing_category',
        'invoice_title',
        'tax_number',
        'company_address',
        'company_phone',
        'bank_name',
        'bank_account',
        'invoice_content',
        'related_tasks',
        'invoice_file_path',
        'status',
        'rejection_reason',
        'express_tracking_number',
        'invoice_remarks',
        'application_time',
        'processed_at',
        'issued_at',
        'created_by',
        'processed_by'
    ];

    protected $casts = [
        'id' => 'string',
        'invoice_amount' => 'decimal:2',
        'invoice_file_path' => 'string',
        'application_time' => 'datetime',
        'processed_at' => 'datetime',
        'issued_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    protected $appends = [
        'billing_type_display',
        'billing_category_display', 
        'status_display',
        'invoice_id'
    ];

    /**
     * 生成雪花ID
     */
    public static function generateSnowflakeId(): string
    {
        // 时间戳（毫秒）
        $timestamp = (int)(microtime(true) * 1000);
        
        // 机器ID（这里使用简单的随机数）
        $machineId = mt_rand(0, 1023); // 10位
        
        // 序列号（这里使用简单的随机数）
        $sequence = mt_rand(0, 4095); // 12位
        
        // 组装雪花ID: 时间戳(42位) + 机器ID(10位) + 序列号(12位)
        $snowflakeId = ($timestamp << 22) | ($machineId << 12) | $sequence;
        
        return (string)$snowflakeId;
    }

    /**
     * 生成发票申请单号
     */
    public static function generateInvoiceNumber(): string
    {
        // 使用微秒时间戳确保唯一性
        $timestamp = str_replace('.', '', microtime(true) * 10000);
        return 'INV' . substr($timestamp, -12) . mt_rand(10, 99);
    }

    /**
     * 创建时自动生成雪花ID和发票单号
     */
    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($model) {
            if (empty($model->id)) {
                $model->id = static::generateSnowflakeId();
            }
            if (empty($model->invoice_number)) {
                $model->invoice_number = static::generateInvoiceNumber();
            }
            if (empty($model->application_time)) {
                $model->application_time = now();
            }
        });
    }

    /**
     * 获取开票类型显示文本
     */
    public function getBillingTypeDisplayAttribute(): string
    {
        $typeMap = [
            self::BILLING_TYPE_6_REGULAR => '6%普票',
            self::BILLING_TYPE_6_SPECIAL => '6%专票',
            self::BILLING_TYPE_DIFFERENTIAL_REGULAR => '差额普票'
        ];

        return $typeMap[$this->billing_type] ?? '未知类型';
    }

    /**
     * 获取开票类目显示文本
     */
    public function getBillingCategoryDisplayAttribute(): string
    {
        $categoryMap = [
            self::BILLING_CATEGORY_IT_SERVICES => '信息技术服务'
        ];

        return $categoryMap[$this->billing_category] ?? '未知类目';
    }

    /**
     * 获取状态显示文本
     */
    public function getStatusDisplayAttribute(): string
    {
        $statusMap = [
            self::STATUS_NEW => '新建',
            self::STATUS_BILLING => '开票中',
            self::STATUS_BILLED => '已开票',
            self::STATUS_REJECTED => '已拒绝',
            self::STATUS_VOIDED => '已作废'
        ];

        return $statusMap[$this->status] ?? '未知状态';
    }

    /**
     * 获取发票ID（显示用）
     */
    public function getInvoiceIdAttribute(): string
    {
        return 'INV' . substr($this->id, -8);
    }

    public function getIdAttribute($value): string
    {
        return (string) $value;
    }

    /**
     * 关联租户
     */
    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    /**
     * 关联落地公司
     */
    public function landingCompany(): BelongsTo
    {
        return $this->belongsTo(LandingCompany::class);
    }

    /**
     * 租户作用域
     */
    public function scopeTenant($query, $tenantId)
    {
        return $query->where('tenant_id', $tenantId);
    }

    /**
     * 开票类型作用域
     */
    public function scopeBillingType($query, $billingType)
    {
        return $query->where('billing_type', $billingType);
    }

    /**
     * 状态作用域
     */
    public function scopeStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    /**
     * 落地公司作用域
     */
    public function scopeLandingCompany($query, $landingCompanyId)
    {
        return $query->where('landing_company_id', $landingCompanyId);
    }

    /**
     * 按发票ID搜索
     */
    public function scopeSearchInvoiceId($query, $invoiceId)
    {
        return $query->where(function ($subQuery) use ($invoiceId) {
            $subQuery->where('invoice_number', 'like', "%{$invoiceId}%")
                ->orWhere('id', 'like', "%{$invoiceId}%");
        });
    }

    /**
     * 按申请时间范围筛选
     */
    public function scopeApplicationTimeRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('application_time', [$startDate, $endDate]);
    }

    /**
     * 获取开票类型选项
     */
    public static function getBillingTypeOptions(): array
    {
        return [
            self::BILLING_TYPE_6_REGULAR => '6%普票',
            self::BILLING_TYPE_6_SPECIAL => '6%专票',
            self::BILLING_TYPE_DIFFERENTIAL_REGULAR => '差额普票'
        ];
    }

    /**
     * 获取开票类目选项（从落地公司获取）
     */
    public static function getBillingCategoryOptions(): array
    {
        $categories = [];
        $companies = LandingCompany::where('status', LandingCompany::STATUS_ACTIVE)
            ->whereNotNull('billing_categories')
            ->get();

        foreach ($companies as $company) {
            if (is_array($company->billing_categories)) {
                foreach ($company->billing_categories as $category) {
                    if (!in_array($category, $categories)) {
                        $categories[] = $category;
                    }
                }
            }
        }

        // 转换为选项格式
        $options = [];
        foreach ($categories as $category) {
            $options[] = [
                'value' => $category,
                'label' => $category
            ];
        }

        return $options;
    }

    /**
     * 获取所有状态选项
     */
    public static function getStatusOptions(): array
    {
        return [
            self::STATUS_NEW => '新建',
            self::STATUS_BILLING => '开票中',
            self::STATUS_BILLED => '已开票',
            self::STATUS_REJECTED => '已拒绝',
            self::STATUS_VOIDED => '已作废'
        ];
    }
}
